package folder.model.node;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;

import folder.model.virtual.VirtualNetwork;
import folder.model.virtual.VirtualNode;

public class NodeAllocation
{
	// Class
	
	private List< Node > nodes;
	public NodeAllocation( List< Node > nodes )
	{
		this.nodes = nodes;
	}
	
	public static NodeAllocation nodeAllocation( List< Node > nodes )
	{
		return new NodeAllocation( nodes );
	}
	
 	// Allocation
	private List< Node > nodesRandom;
	private LinkedHashMap< VirtualNode, Node > matches;
	
	public void run( List< VirtualNode > virtualNodes )
	{
		this.setNodesRandom( virtualNodes.size() );
		this.setMatches( virtualNodes );
		this.allocate();
	}
	
	private void setNodesRandom( int numberVirtualNodes )
	{
		this.nodesRandom = new ArrayList< Node >();
		
		while( this.nodesRandom.size() < numberVirtualNodes )
		{
			int min = 0;
			int max = this.nodes.size() - 1;
			int identifier = min + (int) ( Math.random() * ( max - min + 1 ) );
			Node nodeRandom = this.nodes.get( identifier );
			
			if( !this.nodesRandom.contains( nodeRandom ) )
				if( !nodeRandom.isSelected() )
					this.nodesRandom.add( nodeRandom );
		}
	}
	
	private void setMatches( List< VirtualNode > virtualNodes )
	{
		this.matches = new LinkedHashMap< VirtualNode, Node >();
		
		for( int i = 0; i < virtualNodes.size(); i++ )
		{
			VirtualNode virtualNode = virtualNodes.get( i );
			Node node = this.nodesRandom.get( i );
			this.matches.put( virtualNode, node );
		}
	}
	
	private void allocate()
	{
		Iterator< Entry< VirtualNode, Node > > iterator = this.matches.entrySet().iterator();
		
		while( iterator.hasNext() )
		{
			Entry< VirtualNode, Node > entry = iterator.next();
			VirtualNode virtualNode = entry.getKey();
			Node node = entry.getValue();
			//node.allocate( virtualNode );
			virtualNode.allocate( node );
		}
	}
	
}
